#include "JavaScriptInterpreter.h"

#include "Console.h"

using namespace v8;


Handle<v8::Value> Print(const Arguments& args)
{
	bool first = true;
	for (int i = 0; i < args.Length(); ++i)
		{
			HandleScope handleScope;
			if (first)
				first = false;
			else
				std::cout << ' ';
//				std::cout << *String::AsciiValue(args[i]);
			Console::getSingletonPtr()->print(*(v8::String::AsciiValue(args[i])));
		}
//	Console::getSingletonPtr()->print("\n");
//	std::cout << std::endl;
	return v8::Undefined();
}

//JavaScriptInterpreter::JavaScriptInterpreter(Persistent<Context> ctx) : mContext(ctx)
JavaScriptInterpreter::JavaScriptInterpreter()
{
//	context = Context::New();

	//mOutput = "Google v8 JavaScript engine";
//	Console::getSingletonPtr()->print("v8 JavaScript engine by Google");

	HandleScope handleScope;

	mGlobal = ObjectTemplate::New();
	mGlobal->Set(v8::String::New("print"), FunctionTemplate::New(Print));
	mContext = Context::New(NULL, mGlobal);

	mPrompt = JS_PROMPT;
    mOutput = JS_MSG;	
}

JavaScriptInterpreter::~JavaScriptInterpreter()
{
//	mContext.Dispose();
}

void JavaScriptInterpreter::insertLine(std::string& s)
{
	if(s=="") return;

	HandleScope handle_scope;
	Context::Scope context_scope(mContext);

	TryCatch trycatch;

	Handle<v8::String> source = v8::String::New(s.c_str());

	Handle<v8::Script> script = Script::Compile(source, NULL, NULL);

	if (script.IsEmpty())
		{
			Handle<v8::Value> exception = trycatch.Exception();
			v8::String::AsciiValue exception_str(exception);
			mOutput = *exception_str;
			return;
		}

	Handle<v8::Value> v = script->Run();

	if (v.IsEmpty())
		{
			Handle<v8::Value> exception = trycatch.Exception();
			v8::String::AsciiValue exception_str(exception);
			mOutput = std::string("Exception: ") + *exception_str;
			return;
		}

	if(!v->IsUndefined())
		{
			v8::String::AsciiValue ascii(v);
			mOutput = *ascii;
		}

	mPrompt = JS_PROMPT;
}
